<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item v-if="nowlevel == 1">租户列表</el-breadcrumb-item>
      <el-breadcrumb-item v-if="nowlevel == 2">用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 用户列表主体部分 -->
    <!-- 卡片视图区 -->
    <el-card>
      <el-row :gutter="25">
        <el-col :span="10">
          <!-- 搜索区域 -->
          <el-input
            placeholder="请输入搜索内容"
            v-model="queryInfo.query"
            clearable
            @clear="getUserList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            ></el-button>
          </el-input>
        </el-col>
        <!-- 搜索按钮 -->
        <el-col :span="2">
          <el-button
            v-if="nowlevel == 2"
            type="primary"
            @click="addDialogVisible = true"
            >添加用户</el-button
          >
        </el-col>

        <!-- 让答者变用户 -->
        <el-col :span="2">
          <el-button
            v-if="nowlevel == 2"
            type="primary"
            @click="importDialogVisible = true"
            style="margin-left: 20px"
            >导入用户</el-button
          >
        </el-col>
      </el-row>

      <!-- 用户列表 border边框 stripe隔行变色-->
      <el-table :data="userList" border="" stripe="">
        <!-- 索引列 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column label="用户名" prop="name"></el-table-column>
        <el-table-column label="电话" prop="tel"></el-table-column>
        <el-table-column label="密码" prop="passwd"></el-table-column>

        <el-table-column label="角色" prop="role"></el-table-column>

        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- 修改 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope.row.name)"
            >
            </el-button>
            <!-- 删除 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteUser(scope.row.name, scope.row.level)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div>
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryInfo.pageNum"
          :page-sizes="[1, 2, 5, 100]"
          :page-size="queryInfo.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </el-card>

    <!-- 新增用户对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="70px"
      >
        <el-form-item label="用户名" prop="name">
          <el-input
            v-model="addForm.name"
            placeholder="请输入用户名"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="passwd">
          <el-input
            v-model="addForm.passwd"
            placeholder="请输入密码"
          ></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="tel">
          <el-input v-model="addForm.tel" placeholder="请输入电话"></el-input>
        </el-form-item>
        <el-form-item v-if="nowlevel == 2" label="可发步问卷数" prop="count">
          <el-input-number
            v-model="addForm.count"
            :min="1"
            :max="10"
            label="描述文字"
          ></el-input-number>
        </el-form-item>
      </el-form>

      <!-- 内容底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addUser">确定</el-button>
      </span>
    </el-dialog>

    <!-- 导入用户 -->
    <el-dialog
      title="导入用户"
      :visible.sync="importDialogVisible"
      width="50%"
      @close="importDialogClosed"
    >
      <el-table
        ref="multipleTable"
        :data="answerList"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column prop="name" label="姓名" width="120">
        </el-table-column>
        <el-table-column prop="tel" label="电话" show-overflow-tooltip>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="importDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="importUser">确定</el-button>
      </span>

      <!-- 分页组件 -->
      <div>
        <el-pagination
          @size-change="handleSizeChange1"
          @current-change="handleCurrentChange1"
          :current-page="aqueryInfo.pageNum"
          :page-sizes="[1, 2, 5, 100]"
          :page-size="aqueryInfo.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="atotal"
        >
        </el-pagination>
      </div>
    </el-dialog>

    <!-- 修改对话框 -->
    <el-dialog title="修改用户" :visible.sync="editDialogVisible" width="50%">
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="70px"
      >
        <el-form-item label="用户名" prop="name">
          <el-input v-model="editForm.name" disabled>d</el-input>
        </el-form-item>
        <el-form-item label="电话" prop="tel">
          <el-input v-model="editForm.tel" :disabled="nowlevel != 1"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="passwd">
          <el-input v-model="editForm.passwd"></el-input>
        </el-form-item>
        <el-form-item
          v-if="nowlevel == 2 && editForm.name != nowname"
          label="可发布问卷数"
          prop="count"
        >
          <el-input-number
            v-model="count"
            :min="1"
            :max="10"
            label="描述文字"
          ></el-input-number>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="editUserInfo">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Vue from "vue";
export default {
  created() {
    this.getUserList();
    this.getAnswerList();
  },

  data() {
    return {
      //租户用户
      queryInfo: {
        query: "", //查询信息
        pageNum: 1, //当前页
        pageSize: 5, //每一页最大数
      },

      //答者
      aqueryInfo: {
        query: "", //查询信息
        pageNum: 1, //当前页
        pageSize: 5, //每一页最大数
      },
      userList: [], //用户列表
      total: 0, //租户下的用户总记录数
      answerList: [], // 答者列表
      atotal: 0, //所有答者的记录数
      multipleSelection: [],

      count: 1, //编辑用户设置的可发布问卷数
      addDialogVisible: false, //对话框状态
      importDialogVisible: false, //导入答者

      nowlevel: window.sessionStorage.getItem("level"),
      nowname: window.sessionStorage.getItem("name"),
      //添加表单信息
      addForm: {
        name: "",
        passwd: "",
        tel: "",
        level: "",
        count: "",
        tenantName: window.sessionStorage.getItem("name"),
      },

      //修改用户信息
      editForm: {},
      //显示或者隐藏修改用户栏
      editDialogVisible: false,

      //添加表单验证
      addFormRules: {
        name: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 1,
            max: 12,
            message: "长度在 1 到 12 个字符",
            trigger: "blur",
          },
        ],
        passwd: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 1,
            max: 12,
            message: "长度在 1 到 12 个字符",
            trigger: "blur",
          },
        ],
        tel: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { min: 11, max: 11, message: "请输入正确的手机号", trigger: "blur" },
        ],

        level: [{ required: true, message: "请选择角色", trigger: "blur" }],
        count: [{ required: true, trigger: "blur" }],
      },

      //修改表单验证
      editFormRules: {
        name: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 1,
            max: 12,
            message: "长度在 1 到 12 个字符",
            trigger: "blur",
          },
        ],
        passwd: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 1,
            max: 12,
            message: "长度在 1 到 12 个字符",
            trigger: "blur",
          },
        ],
        tel: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { min: 11, max: 11, message: "请输入正确的手机号", trigger: "blur" },
        ],
        level: [{ required: true, message: "请选择角色", trigger: "blur" }],
      },
      // 下拉框数据更新
      // options: [
      //   {
      //     value: 2,
      //     label: "租户",
      //   },
      //   {
      //     value: 3,
      //     label: "用户",
      //   },
      // ],
      // 设置下拉框默认选中值
      selectvalue: "",
      // 设置下拉框是否被禁用
      selectable: false,
    };
  },
  methods: {
    //获取所有用户 >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>????????????分页没写
    async getUserList() {
      let level = window.sessionStorage.getItem("level");
      let name = window.sessionStorage.getItem("name");
      this.showselect(level);

      await this.$http({
        method: "post",
        url: "/allUser",
        data: {
          query: this.queryInfo.query,
          pageNum: this.queryInfo.pageNum,
          pageSize: this.queryInfo.pageSize,
          name: name,
          level: level,
        },
      }).then((response) => {
        this.userList = response.data.data.list;
        let list = [];
        this.addrole(list);
        this.total = response.data.data.total;
      });
    },

    async getAnswerList() {
      let level = window.sessionStorage.getItem("level");
      let name = window.sessionStorage.getItem("name");
      this.showselect(level);

      await this.$http({
        method: "post",
        url: "/selectAllAnswererY",
        data: {
          query: this.aqueryInfo.query,
          pageNum: this.aqueryInfo.pageNum,
          pageSize: this.aqueryInfo.pageSize,
          name: name,
          level: level,
        },
      }).then((response) => {
        this.answerList = response.data.data.list;
        this.atotal = response.data.data.total;
      });
    },

    // const {data:res} = await this.$http.post("alluser",this.queryInfo);

    addrole(list) {
      this.userList.forEach((user) => {
        // console.log(JSON.stringify(user));
        user = JSON.parse(JSON.stringify(user));

        if (user.level == "2") {
          Vue.set(user, "role", "租户"); //正确姿势
          list.push(user);
        }
        if (user.level == "3") {
          Vue.set(user, "role", "用户"); //正确姿势
          list.push(user);
        }
      });
      this.userList = list;
    },

    //最大数
    handleSizeChange(newSize) {
      this.queryInfo.pageSize = newSize;
      this.getUserList();
    },

    //pageNum触发的动作
    handleCurrentChange(newPage) {
      this.queryInfo.pageNum = newPage;
      this.getUserList();
    },

    handleSizeChange1(newSize) {
      this.aqueryInfo.pageSize = newSize;
      this.getAnswerList();
    },

    //pageNum触发的动作
    handleCurrentChange1(newPage) {
      this.aqueryInfo.pageNum = newPage;
      this.getAnswerList();
    },
    // 用户状态修改
    // async userStateChanged(userInfo) {
    //   const { data: res } = await this.$http.put(
    //     `userstate?id=${userInfo.id}&state=${userInfo.state}`
    //   );
    //   if (res != "success") {
    //     userInfo.id = !userInfo.id;
    //     return this.$message.error("操作失败");
    //   }
    //   this.$message.success("操作成功");
    // },

    //监听添加用户
    addDialogClosed() {
      this.$refs.addFormRef.resetFields();
      this.count = 1;
    },
    //导入用户的关闭
    importDialogClosed() {
      this.count = 1;
    },
    // 增加用户
    addUser() {
      // console.log(typeof(this.addForm.count));
      // console.log(typeof(this.addForm.name));
      this.addForm.count += this.addForm.count + "";
      console.log(typeof this.addForm.count);
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) {
          return;
        }
        //添加用户>>>>>>>>>>>>>>???????????????????表单提交验证
        await this.$http({
          method: "post",
          url: "/createUser",
          data: this.addForm,
        }).then((res) => {
          const response = res.data;
          if (response.code == "666") {
            this.$message.success(response.message);
            this.addDialogVisible = false;
            this.getUserList();
          } else {
            this.$message.error(response.message);
          }
        });
      });
    },

    handleSelectionChange(val) {
      this.multipleSelection = val;
    },

    //前端像后端发送请求
    async importUser() {
      let name = window.sessionStorage.getItem("name"); //获取当前租户名
      const confirmResult = await this.$confirm(
        "确定批量添加这些用户?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (confirmResult != "confirm") {
        //取消
        return this.$message.info("已取消添加");
      }

      //for遍历
      for (var i in this.multipleSelection) {
        // console.log(this.multipleSelection[i].name);
        await this.$http({
          method: "post",
          url: "/tenantCreateUserByAnsList",
          data: {
            tenantName: name,
            userName: this.multipleSelection[i].name,
            count: "5",
          },
        }).then((res) => {
          if (res.data.code == "666") {
            // console.log(res)
            this.$message.success(res.data.message);
            this.getUserList();
            this.getAnswerList();
          } else {
            this.$message.error(res.data.message);
          }
        });
      }
      this.importDialogVisible = false; //关闭
    },
    //根据主键删除用户
    async deleteUser(name, level) {
      const confirmResult = await this.$confirm(
        "此操作将永远删除用户，是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (confirmResult != "confirm") {
        //取消
        return this.$message.info("已取消删除");
      }
      await this.$http({
        method: "post",
        url: "/deleteUser",
        data: {
          name: name,
          level: level,
        },
      }).then((res) => {
        if (res.data.code == "666") {
          // console.log(res)
          this.$message.success(res.data.message);
          this.getUserList();
        } else {
          this.$message.error(res.data.message);
        }
      });
    },

    //显示对话框
    async showEditDialog(name) {
      const { data: res } = await this.$http.get("getUpdate?name=" + name);

      // console.log(res.data);
      this.editForm = res.data; //查询出用户信息反填回编辑表单
      this.editDialogVisible = true;
    },

    //关闭窗口
    editDialogClosed() {
      this.$refs.editFormRef.resetFields(); //重置信息
    },

    //确认修改
    editUserInfo() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) {
          return;
        }
        await this.$http({
          method: "post",
          url: "/editUser",
          data: this.editForm,
        }).then((res) => {
          if (res.data.code == "666") {
            this.$message.success(res.data.message);
            //隐藏
            this.editDialogVisible = false;
            this.getUserList();
          } else {
            this.$message.error(res.data.message);
          }
        });
      });
    },

    //   //确认修改
    // countUserInfo() {

    // },

    showselect(level) {
      if (level == "1") {
        this.selectable = false;
      } else {
        this.selectable = true;
        this.addForm.level = "3";
      }
    },
  },
};
</script>

<style lang="less" scoped>
/* 面包屑样式 */
.el-breadcrumb {
  margin-bottom: 15px;
  font-size: 17px;
}
</style>